<?php
/**
 * Author: MeiJay
 * Date: 2020/3/10 15:47
 * Time: 9:44
 * Desc:
 */


namespace App\Admin\Services;


use App\Jobs\PurchaseOrderDownloadGoodImageJob;
use App\Model\Address;
use App\Model\PurchaseOrder;
use App\Model\PurchaseOrderDetail;
use Encore\Admin\Facades\Admin;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;

class PurchaseService
{

    /**
     * 导入订货单
     * @param array $insert
     * @return int
     * @author: 梅杰 2020/3/15 12:52
     */
    public function import(array $insert)
    {
        // 分发给不同的供应商生成相关的订单
        $preHandle = Collection::make($insert);
        $groupPurchaseOrders = $preHandle->groupBy('supplier_id');
        $successCount = 0;
        $orderIds = [];
        foreach ($groupPurchaseOrders as $supplier => $groupPurchaseOrder) {
            DB::beginTransaction();
            try {
                // 导入记录
                $purchaseOrder = PurchaseOrder::query()->create([
                    'operator_id' => Admin::user()->id,
                    'supplier_id' => $supplier
                ]);
                $orderIds[] = $purchaseOrder->id;

                $data = [];
                foreach ($insert as $sku) {
                    unset($sku['supplier_id']);
                    $sku['purchase_order_id'] = $purchaseOrder->id;
                    $data[] = $sku;
                }

                PurchaseOrderDetail::query()->insert($data);

            } catch (\Exception $exception) {
                DB::rollBack();
                continue;
            }
            $successCount += count($groupPurchaseOrder);
            DB::commit();
        }
        if ($orderIds) {
            $this->preHandleExport($orderIds);
        }

        return $successCount;
    }


    /**
     * 处理订货单中的商品图片
     *
     * @param array $purchaseOrderIds
     * @author: 梅杰 2020/3/15 12:55
     */
    public function preHandleExport(array $purchaseOrderIds)
    {
        // 获取当前
        $purchaseOrder = PurchaseOrderDetail::query()
            ->whereIn('purchase_order_id', $purchaseOrderIds)
            ->get(['id', 'good_id']);

        // 生成一条下载记录

        foreach ($purchaseOrder as $value) {
            dispatch(new PurchaseOrderDownloadGoodImageJob($value->id, $value->good_id));
        }
    }

    /**
     * 获取不能指定订货单id数组中不能导出的订货单
     *
     * @param array $purchaseOrderIds
     * @return Builder[]|\Illuminate\Database\Eloquent\Collection
     * @author: 梅杰 2020/3/15 13:01
     */
    public function checkDownload(array $purchaseOrderIds)
    {
        return PurchaseOrderDetail::query()
            ->whereIn('purchase_order_id', $purchaseOrderIds)
            ->where('is_handle', 0)
            ->groupBy('purchase_order_id')
            ->get(['purchase_order_id', DB::raw("count(*) as notHandleCount")]);
    }


    /**
     * 导出
     *
     * @param int $purchaseOrderId
     * @return \Illuminate\Http\RedirectResponse
     * @author: 梅杰 2020/3/15 13:45
     */
    public function export(int $purchaseOrderId)
    {
        // 获取商品数据
        $goods = $this->getGoodData($purchaseOrderId);

        $spreadsheet = new Spreadsheet();
        try {
            $excelSheet = $spreadsheet->getActiveSheet();
        } catch (Exception $e) {
            admin_toastr('导出失败', 'error');
            return back();
        }
        $timeData = PurchaseOrder::query()->find($purchaseOrderId, ['created_at']);
        $address = Address::query()->first(['address'])->address ?? '暂无';
        $objPHPExcel = $excelSheet->setCellValue("A1", "常州刘娟" . $timeData->created_at . "订货单")
            ->setCellValue("A2", "收货地址：" . $address)
            ->setCellValue("A3", '货号')
            ->setCellValue("B3", '颜色')
            ->setCellValue("C3", '图片')
            ->setCellValue("D3", '数量');

        $objPHPExcel->getColumnDimension('A')->setWidth(12);
        $objPHPExcel->getColumnDimension('B')->setWidth(12);
        $objPHPExcel->getColumnDimension('C')->setWidth(15);
        $objPHPExcel->getColumnDimension('D')->setWidth(12);


        $k = 4;
        foreach ($goods as $good) {
            $objPHPExcel->setCellValue('A' . $k, $good->good->number);
            $objPHPExcel->setCellValue('B' . $k, $good->good->color);
            $objPHPExcel->setCellValue('D' . $k, $good->count);

            if ($good->img_path) {

                $objPHPExcel->getRowDimension($k)->setRowHeight(76);
                $objDrawing = new Drawing();
                $objDrawing->setResizeProportional(false);
                $objDrawing->setCoordinates("C$k");

                try {
                    $objDrawing->setPath(storage_path('app/' . $good->img_path));
                    $objDrawing->setWorksheet($excelSheet);
                } catch (Exception $e) {
                    $objPHPExcel->setCellValue('C' . $k, '图片插入失败：' . $e->getMessage());

                }
                $objDrawing->setOffsetX(8);
                $objDrawing->setOffsetY(8);

                $objDrawing->setHeight(80);
                $objDrawing->setWidth(80);

            } else {
                $objPHPExcel->setCellValue('C' . $k, '');
            }
            $k++;
        }

        try {
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        } catch (\PhpOffice\PhpSpreadsheet\Writer\Exception $e) {
            admin_toastr('导出失败', 'error');
            return back();
        }

        try {
            $fileName = "order_" . date('YmdHis');
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $writer->save('php://output');
        } catch (\PhpOffice\PhpSpreadsheet\Writer\Exception $e) {
            admin_toastr('导出失败', 'error');
            return back();
        }
        return back();
    }

    /**
     * 获取订货单详情的商品数据
     *
     * @param int $purchaseOrderId
     * @return Builder[]|\Illuminate\Database\Eloquent\Collection
     * @author: 梅杰 2020/3/15 13:50
     */
    public function getGoodData(int $purchaseOrderId)
    {
        return PurchaseOrderDetail::query()->select(['good_id', 'count', 'img_path'])
            ->where('purchase_order_id', $purchaseOrderId)
            ->with('good:id,number,color')
            ->get();
    }
}
